package com.tanhua.server.service;

import com.tanhua.commons.pojo.IMessage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.UserLocationDTO;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TanhuaService {
    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserLocationApi userLocationApi;
    @Reference
    private FriendApi friendApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;
    @Reference
    private UserLikeApi userLikeApi;

    public ResponseEntity todayBest() {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //查询当前用户缘分值最高的
        RecommendUser recommendUser = recommendUserApi.findMaxScoreUser(userId);
        if (recommendUser == null) {
//            如果没有查询到，就给一个默认的
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L);
            recommendUser.setScore(95D);
        }
        //根据recommendUser找到推荐的用户信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        //构造返回值
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setFateValue(recommendUser.getScore().intValue());
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        System.out.println(vo);
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity recommendation(RecommendUserQueryVO vo) {
        //获取当前用户
        User user = UserHolder.getUser();
        //查询出当前用户的推荐
        PageResult<RecommendUser> pageResult = recommendUserApi.recommendation(user.getId(), vo.getPage(), vo.getPagesize());
        //判断推荐是否为空，为空就添加假数据
        List pageResultItems = pageResult.getItems();
        if (pageResultItems == null || pageResultItems.size() == 0) {
            pageResultItems = new ArrayList();
            String ids = "1,2,3,4,5,6,7,8,9";
            for (String id : ids.split(",")) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(id));
                recommendUser.setScore(RandomUtils.nextDouble(70, 89));
                pageResultItems.add(recommendUser);
            }
            pageResult = new PageResult(9, vo.getPagesize(), 1, vo.getPage(), pageResultItems);
        }
        //转换成RecommendUserVO列表
        List<RecommendUserVO> voList = new ArrayList<>();
        for (RecommendUser recommendUser : pageResult.getItems()) {
            //查询推荐用户的userInfo
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            //转换成RecommendUserVO
            RecommendUserVO userVO = new RecommendUserVO();
            BeanUtils.copyProperties(userInfo, userVO);
            if (userInfo.getTags() != null) {
                userVO.setTags(userInfo.getTags().split(","));
            }
            //设置缘分值
            userVO.setFateValue(recommendUser.getScore().intValue());
            //储存到voList中
            voList.add(userVO);
        }
        //构造返回值
        PageResult<RecommendUserVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    public ResponseEntity personalInfo(Long id) {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //根据id查询推荐
        RecommendUser recommendUser = recommendUserApi.findByIdSorce(userId, id);
        //查询个人信息
        UserInfo userInfo = userInfoApi.findById(id);
        //构造返回值
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(userInfo.getTags().split(","));
        if (recommendUser == null) {
            vo.setFateValue((int) RandomUtils.nextDouble(70, 95));
        } else {
            vo.setFateValue(recommendUser.getScore().intValue());
        }
        return ResponseEntity.ok(vo);
    }

    //交友-查看陌生人问题
    public ResponseEntity findStrangerQuestion(Long userId) {
        Question question = questionApi.findByUserId(userId);
        if (question == null) {
            question = new Question();
            question.setTxt("杰桑，阳光明媚吗？");
        }
        return ResponseEntity.ok(question.getTxt());
    }

    //交友-回复陌生人问题
    public ResponseEntity replyStrangerQuestions(Long targetUserId, String reply) {
        //获取当前用户信息
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        //获取对方的陌生人问题
        Question question = questionApi.findByUserId(targetUserId);
        String questionText = question == null ? "杰桑，阳光明媚吗？" : question.getTxt();

        //封装对象信息
        IMessage iMessage = new IMessage();
        iMessage.setNickname(userInfo.getNickname());
        iMessage.setReply(reply);
        iMessage.setUserId(UserHolder.getUserId().toString());
        iMessage.setStrangerQuestion(questionText);
        //调用环信API，给用户发送消息（回复陌生人问题）
        huanXinTemplate.sendMsg(targetUserId.toString(), iMessage);

        return ResponseEntity.ok(null);
    }


    public ResponseEntity searchNear(String gender, Integer distance) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用api，搜索附近的人
        List<UserLocationDTO> list = userLocationApi.searchNear(userId, distance);
        //转换成vo ，排除不符合的人
        List<NearUserVO> voList = new ArrayList<>();
        for (UserLocationDTO userLocation : list) {
            //排除自己
            if (userLocation.getUserId() == userId.intValue()) {
                continue;
            }
            //查找附近人的详细信息
            UserInfo userInfo = userInfoApi.findById(userLocation.getUserId());
            //排除性别不符合的
            if (!userInfo.getGender().equals(gender)) {
                continue;
            }

            NearUserVO vo = new NearUserVO();
            vo.setUserId(userInfo.getId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());
            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }

    /**
     * 探花-左滑右滑
     *
     * @return
     */
    public ResponseEntity cards() {
        //查询附近的人列表信息
        List<UserInfo> userList = userInfoApi.find();
        //转成vo对象
        List<UserInfoVO> voList = new ArrayList<>();
        String value = redisTemplate.opsForValue().get("LOVE" + UserHolder.getUserId());
        if (value == null) {
            value = "";
        }
        for (UserInfo userInfo : userList) {
            if (value.contains(userInfo.getId().toString())) {
                continue;
            }
            UserInfoVO vo = new UserInfoVO();
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
            voList.add(vo);
        }
        return ResponseEntity.ok(voList);
    }

    /**
     * 喜欢
     *
     * @param likeUserId
     * @return
     */
    public ResponseEntity love(Long likeUserId) {

        //判断是否互为好友关系
        UserLike userLike = userLikeApi.userList(UserHolder.getUserId(), likeUserId);
        if (userLike == null) {
            userLikeApi.singleLove(UserHolder.getUserId(), likeUserId);
            String value = redisTemplate.opsForValue().get("LOVE" + UserHolder.getUserId());
            if (value == null) {
                value = "";
            }
            value = value + "," + likeUserId;
            redisTemplate.opsForValue().set("LOVE" + UserHolder.getUserId(), value);
        } else {
            userLikeApi.delete(UserHolder.getUserId(), likeUserId);
            friendApi.addFriend(UserHolder.getUserId(), likeUserId);
        }

        return ResponseEntity.ok(null);
    }

    /**
     * 不喜欢
     *
     * @param likeUserId
     * @return
     */
    public ResponseEntity unlove(Long likeUserId) {

        userLikeApi.delete(UserHolder.getUserId(), likeUserId);
        String value = redisTemplate.opsForValue().get("LOVE" + UserHolder.getUserId());
        if (value == null) {
            value = "";
        }
        value = value + "," + likeUserId;
        redisTemplate.opsForValue().set("LOVE" + UserHolder.getUserId(), value);
        return ResponseEntity.ok(null);
    }
}
